﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;
using Dapper;

//通达信主题收集
namespace HotTopic.collector
{
    class TdxCollector : AbstractCollector
    {
        private static String TdxPath = Config.TdxPath;

//        private static void Main(string[] args)
//        {
//            TdxCollector collector = new TdxCollector();
//            Dictionary<String, List<String>> area = collector.GetAreaMap();
//            var concept = collector.GetConceptMap();
//            var industry = collector.GetIndustryMap();
//            Console.ReadKey();
//        }
        //返回：行业名称=>股票代码列表
        protected override Dictionary<string, List<string>> GetIndustryMap()
        {
            var dicIndustryCodeToName = GetIndustryConfig();
            var dicStockToIndustryCode = GetStockIndustryCode();
            var dic = new Dictionary<String,List<String>>();
            var strCon = @"Driver={Microsoft dBase Driver (*.dbf)};DefaultDir=" + TdxPath + @"\T0002\hq_cache";
            using (OdbcConnection connection = new OdbcConnection(strCon))
            {
                var rows = connection.Query("select * from base.dbf");
                foreach (var dr in rows)
                {
                    String sc = dr.SC.ToString().Trim();
                    String market = sc.Equals("0") ? "SZ" : sc.Equals("1") ? "SH" : "?";
                    String code = dr.GPDM.ToString().Trim();
                    String stockCode = $"{code}.{market}";

                    if (!dicStockToIndustryCode.ContainsKey(code))
                    {
                        continue;
                    }
                    String industryCode = dicStockToIndustryCode[code];
                    //行业代码小于5不是二级行业
                    if (industryCode.Length < 5)
                    {
                        continue;
                    }
                    
                    var industrySecondCode = industryCode.Substring(0, 5);
                    if (!dicIndustryCodeToName.ContainsKey(industrySecondCode))
                    {
                        continue;
                    }
                    String industryName = dicIndustryCodeToName[industrySecondCode];
                    if (!dic.ContainsKey(industryName))
                    {
                        dic.Add(industryName,new List<string>());
                    }
                    dic[industryName].Add(stockCode);
                }
            }
            return dic;
        }

        //返回：概念名称=>股票代码列表
        protected override Dictionary<string, List<string>> GetConceptMap()
        {
            String path = $@"{TdxPath}\T0002\hq_cache\block_gn.dat";
            List<String> list;
            using (StreamReader reader = new StreamReader(path, Encoding.Default))
            {
                String strAllFile = reader.ReadToEnd().Remove(0, 384).Replace("\u0001", "\0").Replace("\0", "|");
                var arrLines = strAllFile.Split('|');
                list = arrLines.Where(x => !String.IsNullOrEmpty(x)).ToList();
            }
            
            var dic = new Dictionary<String,List<String>>();
            var xName = "";
            var indexStx = int.MaxValue;
            for (var i = 0; i < list.Count; i++)
            {
                var str = list[i];
                if (str.EndsWith("\u0002"))
                {
                    if (dic.ContainsKey(xName))
                    {
                        if (str.Length == 1)
                        {
                            dic[xName].RemoveAt(dic[xName].Count - 1);
                            dic[xName].RemoveAt(dic[xName].Count - 1);
                        }
                        else
                        {
                            dic[xName].RemoveAt(dic[xName].Count - 1);
                        }
                    }

                    indexStx = i;
                    xName = str.Length == 1 ? list[i - 2] : list[i - 1];
                    if (!dic.ContainsKey(xName))
                    {
                        dic.Add(xName, new List<string>());
                    }
                }

                if (i > indexStx)
                {
                    dic[xName].Add(list[i].Substring(0, 1) == "6" ? list[i] + ".SH" : list[i] + ".SZ");
                }
            }
            return dic;
        }

        //返回：地区名称=>股票代码列表
        protected override Dictionary<string, List<string>> GetAreaMap()
        {
            Dictionary<string, string> areaConfig = GetAreaConfig();
            if (areaConfig == null)
            {
                return new Dictionary<string, List<string>>();
            }
            Dictionary<string, List<string>> areaMap = new Dictionary<string, List<string>>();

            var strCon = @"Driver={Microsoft dBase Driver (*.dbf)};DefaultDir=" + TdxPath + @"\T0002\hq_cache";
            using (OdbcConnection connection = new OdbcConnection(strCon))
            {
                var rows = connection.Query("select * from base.dbf");
                foreach (var dr in rows)
                {
                    String sc = dr.SC.ToString().Trim();
                    String market = sc.Equals("0") ? "SZ" : sc.Equals("1") ? "SH" : "?";
                    String code = dr.GPDM.ToString().Trim();
                    String areaCode = dr.DY.ToString().Trim();
                    if (!areaConfig.ContainsKey(areaCode))
                    {
                        continue;
                    }
                    String areaName = areaConfig[areaCode].Replace("板块", "");
                    if (!areaMap.ContainsKey(areaName))
                    {
                        areaMap.Add(areaName, new List<string>());
                    }
                    String stockCode = $"{code}.{market}";
                    areaMap[areaName].Add(stockCode);
                }
            }
            return areaMap;
        }

        //返回 ：地区代码=>地区名字
        private Dictionary<string, string> GetAreaConfig()
        {
            String TdxPath = ConfigurationManager.AppSettings["tdxpath"];
            var path = $@"{TdxPath}\T0002\hq_cache\tdxzs.cfg";
            using (StreamReader sr = new StreamReader(path, Encoding.Default))
            {
                var dic = new Dictionary<string, string>();
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    var a = line.Split('|');
                    if (a[2] == "3")
                    {
                        var areaName = a[0];
                        var areaCode = a[5];
                        dic.Add(areaCode, areaName);
                    }
                }
                return dic;
            }
        }
        /// <summary>
        /// 获取行业代码表
        /// </summary>
        /// <returns>
        /// 行业代码=>行业名字
        /// </returns>
        private  Dictionary<string, string> GetIndustryConfig()
        {
            var path = $@"{TdxPath}\incon.dat";
            using (StreamReader sr = new StreamReader(path, Encoding.Default))
            {
                string line;
                var dic = new Dictionary<string, string>();
                var isStart = false;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains("######"))
                    {
                        isStart = false;
                    }
                    if (isStart)
                    {
                        var a = line.Split('|');
                        var industryCode = a[0];
                        var industryName = a[1];
                        dic.Add(industryCode, industryName);
                    }
                    if (line.Contains("#TDXNHY"))
                    {
                        isStart = true;
                    }
                }
                return dic;
            }
        }

        /// <summary>
        /// 获取股票对应的行业代码
        /// </summary>
        /// <returns>
        /// 股票代码=>行业代码
        /// </returns>
        private static Dictionary<string, string> GetStockIndustryCode()
        {
            var path = $@"{TdxPath}\T0002\hq_cache\tdxhy.cfg";
            using (StreamReader sr = new StreamReader(path, Encoding.Default))
            {
                string line;
                var dic = new Dictionary<string, string>();
                while ((line = sr.ReadLine()) != null)
                {
                    var a = line.Split('|');
                    var stockCode = a[1];
                    var industryCode = a[2];
                    dic.Add(stockCode, industryCode);
                }
                return dic;
            }
          
        }
    }
}